import json
from django.http import HttpResponse,JsonResponse
from django.shortcuts import render,reverse, redirect


# Create your views here.

def weather(request, city, year):
    # 演示用正则组抽取url中的参数:位置参数
    print(city)
    print(year)

    return HttpResponse('weather')


def weather2(request, city, year):
    # 演示用正则组抽取url中的参数:关键字参数
    print(city)
    print(year)

    return HttpResponse('weather2')


def query_str(request):
    a = request.GET.get('a')  # 一键一值,如果多值会取到最后一个
    b = request.GET.get('b')
    a_list = request.GET.getlist('a')  #一键多值,返回列表
    return HttpResponse('requery_str')


def body_form(request):
    """演示提取请求体中的表单数据"""
    # 提取请求休中的表单数据用 POST
    # request.POST  返回一个QueryDict 类型的对象,类似字典
    like = request.POST.get('like')
    b = request.POST.get('b')
    like_list = request.POST.getlist('like')

    return HttpResponse('body_form')


# POST /body_json/
def body_json(request):
    """演示提取请求体中的非表单数据 json"""
    bytes_str = request.body  # 获取请求体中的非表单数据,类型是字节类型
    json_str = bytes_str.decode()  # 将二进制转换成字符串
    json_dict = json.loads(json_str)  # 将json格式的字符串转换成json字典

    return HttpResponse('body_json')


def request_head(request):
    con_type = request.META["CONTENT_TYPE"]
    print(con_type)
    print(request.method, request.path)

    return HttpResponse("request_head")


def request_demo(request):

    # HttpResponse(content=响应体,content_type=响应体数据类型,status=状态码)
    # return HttpResponse("request_demo"),
    # return HttpResponse("request_demo",content_type="text/plain",status=204)
    response = HttpResponse("ok")
    response["itcast"] = 'python'
    return response


def request_json(request):
    # 演示响应json数据
    # json中的引号一定要用双引号
    json_dict = {"name": "cg", "age": "18"}
    return JsonResponse(json_dict)


def reverse_demo(request):
    # 演示路由的命名空间和反向解析
    # 正向解析:通过路由找视图
    # 反向解析:通过视图找路由
    url = reverse("request_response:reverse_demo")
    print(url)
    return HttpResponse("reverse_demo")


# GET/redirect_demo/
def redirect_demo(request):
    # 演示重定向
    # 在路径前加/表示从根目录开始拼接
    # return redirect("/users/index")
    # 重定向配合反向解析
    return redirect(reverse("users:reverse_demo"))

# GET/cookie_demo/
def cookie_demo(request):
    """cookie缓存数据读写"""
    # 设置cookie需要通过响应对象设置
    response = HttpResponse("cookie_demo")
    # set_cookie(key, velue,过期时间)
    response.set_cookie("name","chaoge",max_age=3600)
    # 读取cookie数据,需要通过请求对象
    name = request.COOKIES.get("name")
    print(name)
    return response


# GET/session_demo/
def session_demo(request):
    """session缓冲读写"""
    # 设置session session它是依赖cookie
    request.session["name"] = 'xcg'
    # 存储session时,它会自动生成一个session_id
    # 后面会把这个session_id通过响应对象写入到浏览器cookie中
    #读取session
    name = request.session.get("name")
    # 通过request带过来的cookie 它里面有session_id
    # 通过session_id就可以取出对应的那条session记录
    # 在通过name 取到 xcg
    print(name)

    return HttpResponse("session_demo")